<!-- 别人的代码 ，借鉴用 -->

<template>
  <div>
    <Navmenu></Navmenu>
    <el-container>
      <el-header>
        <!-- 快速导航栏 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>课程管理</el-breadcrumb-item>
          <el-breadcrumb-item>我的课程</el-breadcrumb-item>
        </el-breadcrumb>
        <el-divider></el-divider>
      </el-header>

      <el-main>
        <!-- 卡片视图区域 -->
        <el-card>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getCouList">
                <el-button slot="append" icon="el-icon-search" @click="getCouList"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <!-- 添加课程按钮 -->
              <el-button type="primary" @click="addCouVisible=true">添加课程</el-button>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-table :data="coulist" border stripe >
            <el-table-column type="index"></el-table-column>
            <el-table-column label="课程名" prop="name"></el-table-column>
            <el-table-column label="类别" prop="classname"></el-table-column>
            <el-table-column label="开课教师" prop="teaname"></el-table-column>
            <el-table-column label="状态" prop="status">
              <template slot-scope="scope">
                <div v-if="scope.row.status">已开启</div>
                <div v-if="!scope.row.status">待通过</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="310px">
              <template slot-scope="scope">
                <!-- 进入课程按钮 -->
                <el-button
                  type="warning"
                  icon="el-icon-search"
                  @click="intoCou(scope.row.couid)"
                  :disabled="!scope.row.status"
                >进入课程</el-button>
                <!-- 章节设置按钮 -->
                <el-button
                  type="success"
                  icon="el-icon-setting"
                  :disabled="!scope.row.status"
                  @click="setChapButton(scope.row.couid)"
                >设置章节</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页区域 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[3,5,10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-card>
      </el-main>
    </el-container>

    <!-- 添加课程对话框 -->
    <el-dialog title="添加课程" :visible.sync="addCouVisible" width="50%" @close="addCouClosed">
      <!-- 内容主题区域 -->
      <el-form :model="addCouForm" ref="addCouRef" label-width="70px">
        <el-form-item label="课程名" prop="name">
          <el-input v-model="addCouForm.name" placeholder="请输入课程名"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="classname">
          <el-input v-model="addCouForm.classname" placeholder="请输入类别"></el-input>
        </el-form-item>
        <el-form-item label="详细介绍" prop="info">
          <el-input
            rows="5"
            type="textarea"
            placeholder="请输入课程介绍"
            v-model="addCouForm.info"
            :disabled="false"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="url">
          <el-upload
            class="upload-demo"
            action
            :http-request="Upload"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">上传封面</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCouVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCou()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 章节设置对话框 -->
    <el-dialog title="章节设置" :visible.sync="setChapVisible" width="55%">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item
          v-for="(chap, index) in ChapList"
          :key="index"
          :title="chap.chapname"
          :name="chap.activeName"
        >
          <el-card>
            <el-row>
              小节列表：
              <el-button
                size="mini"
                type="success"
                icon="el-icon-edit"
                class="addsecbutton"
                @click="addSecButton(chap.chapname)"
              >
                <!-- //添加小节按钮 -->
                添加小节
              </el-button>
            </el-row>
            <el-row>
              <el-table :data="chap.seclist" border stripe>
                <!-- 小节列表（name url 删除操作） -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="小节名" prop="secname"></el-table-column>
                <el-table-column label="视频url" prop="url"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- 删除小节 -->
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteSec(scope.row,index)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-card>
        </el-collapse-item>
      </el-collapse>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-popover placement="top" width="160" v-model="popoverVisible">
          <el-input v-model="tempchapname" placeholder="请输入章节名"></el-input>
          <div style="text-align: right; margin: 0;margin-top: 15px;">
            <el-button size="mini" type="text" @click="popoverVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="addChap()">确定</el-button>
          </div>
          <el-button type="success" slot="reference" class="a1">添加章节</el-button>
        </el-popover>
        <el-button @click="setChapVisible = false">取 消</el-button>
        <el-button type="primary" @click="setChap()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加小节对话框 -->
    <el-dialog title="添加小节" :visible.sync="addSecVisible" width="50%" @close="addSecClosed">
      <el-form :model="tempseclist" ref="addSecRef">
        <el-form-item label="小节名:" prop="secname">
          <el-input v-model="tempseclist.secname" placeholder="请输入小节名"></el-input>
        </el-form-item>
        <el-form-item label="视频:" prop="url">
          <el-upload
            class="upload-demo"
            action
            :http-request="multipartUpload"
            :file-list="fileList2"
            list-type="picture"
          >
            <el-button size="small" type="primary">上传视频</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addSecVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSec()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  import Navmenu from "../common/nav";
  export default {
    components: {Navmenu},
    data() {
      return {
        //检索
        queryInfo: {
          query: "",
          pagenum: 1,
          pagesize: 3
        },
        //课程列表
        coulist: [
          {
            couid: 1,
            name: "123",
            teaname: "swq",
            classname: "前端开发",
            status: false
          },
          {
            couid: 2,
            name: "123",
            teaname: "s11wq",
            classname: "后端开发",
            status: true
          }
        ],
        //检索到的条数
        total: 0,
        addCouVisible: false,
        //添加课程表单
        addCouForm: {
          name: "",
          classname: "",
          info: "",
          url: "",
          username: ""
        },
        //上传图片显示表
        fileList: [],
        //上传视频显示表
        fileList2: [],
        //章节设置显示框
        setChapVisible: true,
        //折叠面板激活
        activeName: "1",
        //章节信息
        ChapList: [
          {
            chapname: "第一章",
            activeName: "1",
            seclist: [
              {
                secname: "1",
                url: "http"
              },
              {
                secname: "2",
                url: "http"
              }
            ]
          }
        ],
        //添加章节按钮的popover显示
        popoverVisible: false,
        //添加章节按钮的popover文本框内容，用于添加章节
        tempchapname: "",
        //添加小节按钮按后的小节名与yrl
        tempseclist: {
          secname: "",
          url: ""
        },
        //用于向添加小节对话框传输章节数据
        nowchap: "",
        //添加章节对话框的显示
        addSecVisible: false,
        loading: true
      };
    },
    created() {
      this.getCouList();
    },
    methods: {
      //交互//获取该教师开设的课程列表
      async getCouList() {
        //获取该教师开设的课程列表
        //要求返回一个list
        //list[0]为查找到的数据条数，类型int
        //list[1]中嵌套一个list，为课程信息表
        // coulist: [
        //       {
        //           couid: 1,
        //           name: "123",
        //           teaname: "swq",
        //           classname: "前端开发"
        //       },
        //       {
        //           couid: 1,
        //           name: "123",
        //           teaname: "swq",
        //           classname: "前端开发"
        //       }
        //   ]
        //
        //     query:  /*搜索框内内容，用于课程名模糊查询*/
        //     pagenum: /*分页第n页*/
        //     pagesize: /*一页有几个元素*/
        //     username: /*该教师的username*/
        let res = await this.$http.get("getcoulist", {
          params: {
            query: this.queryInfo.query,
            pagenum: this.queryInfo.pagenum,
            pagesize: this.queryInfo.pagesize,
            username: window.sessionStorage.getItem("username")
          }
        });
        if (res.status !== 200) {
          return this.$message.error("获取列表失败");
        }
        console.log(res)
        this.coulist = res.data[1];
        this.total = res.data[0];
      },

      //监听pagesize改变的事件
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize;
        this.getCouList();
      },

      //监听 页码值 改变的事件
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage;
        this.getCouList();
      },
      //进入该课程的管理页面
      intoCou(couid) {
        window.sessionStorage.setItem("couid", couid);
        window.location.replace("/#/intocou");
      },

      //监听 添加课程框的关闭
      addCouClosed() {
        this.$refs.addCouRef.resetFields();
        //console.log(this.addCouForm)
        this.fileList.splice(0, this.fileList.length);
      },
      //交互//添加课程
      async addCou() {
        //添加课程
        // addCouForm: {
        //     name: "", //课程名
        //     classname: "", //类型
        //     info: "", //详细介绍
        //     url:"", //封面图片url
        //     username:"" //教师id
        //   }
        //
        //  方法：post
        //  返回参数类型：Result   成功添加返回200  不成功400
        //
        this.addCouForm.username = window.sessionStorage.getItem("username");
        let res = await this.$http.post("addcou", this.addCouForm);
        console.log(res)
        if (res.data.code !== 200) {
          return this.$message.error("添加课程失败!");
        }
        this.$message.success("添加课程成功!");
        //表单隐藏
        this.addCouVisible = false;
        //重新获取课程列表
        this.getCouList();
      },

      //上传图片方法
      async Upload(file) {
        //console.log(file.file.name)
        var fileName = "courseimg/" + file.file.uid + "/" + file.file.name;
        //定义唯一的文件名，打印出来的uid其实就是时间戳,/前为文件夹
        let res = await client().put(fileName, file.file);
        console.log(res);
        this.addCouForm.url =
          "https://xmutswq.oss-cn-hangzhou.aliyuncs.com/" + fileName;
        //console.log(this.addCouForm)
      },

      //交互//章节设置按钮，需从后端获取章节数据~~~~~~~~~~未完成
      async setChapButton(couid) {
        //console.log(couid)
        window.sessionStorage.setItem("couid",couid)
        //要写一个从后端获取章节数据的方法
        let res = await this.$http.get("getchaplist",{params:{couid: couid}});
        console.log(res)
        this.ChapList=res.data;
        this.setChapVisible = true;
      },

      //添加章节功能
      addChap() {
        var length = this.ChapList.length;
        length = length + 1;
        length = length + "";
        //console.log(length)
        this.ChapList.push({
          chapname: this.tempchapname,
          activeName: length,
          seclist: []
        });
        //console.log(this.ChapList)
        this.popoverVisible = false;
      },
      //添加小节功能
      addSec() {
        for (var i = 0; i < this.ChapList.length; i++) {
          if (this.ChapList[i].chapname == this.nowchap) {
            this.ChapList[i].seclist.push({
              secname: this.tempseclist.secname,
              url: this.tempseclist.url
            });
            this.$message.success("成功添加小节");
            this.addSecVisible = false;
            return;
          }
        }
        this.addSecVisible = false;
        return this.$message.error("添加小节失败");
      },
      //分片上传视频
      async multipartUpload(file) {
        //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
        var videoName = "coursevideo/" + file.file.uid + "/" + file.file.name;

        let result = await client().multipartUpload(videoName, file.file);
        this.tempseclist.url =
          "https://xmutswq.oss-cn-hangzhou.aliyuncs.com/" + videoName ;
        console.log("tempseclist:" + this.tempseclist);
        console.log(result);
      },
      //添加小节表单域重置
      addSecClosed() {
        //表单重置
        this.$refs.addSecRef.resetFields();
        //console.log(this.fileList2)
        //文件表重置
        this.fileList2.splice(0, this.fileList2.length);
        //console.log(this.fileList2)
      },
      //添加小节按钮 需传入其所对应章节的章节名，然后赋值给nowchap，供添加小节对话框使用
      addSecButton(chapname) {
        this.nowchap = chapname;
        this.addSecVisible = true;
      },
      //删除小节功能 需提供章节与小节名
      deleteSec(son, dad) {
        //小节名
        // console.log(son.secname)
        //章节序号
        //console.log(dad)

        for (var i = 0; i < this.ChapList[dad].seclist.length; i++) {
          if (this.ChapList[dad].seclist[i].secname == son.secname) {
            //console.log("找到该小节了")
            this.ChapList[dad].seclist.splice(i, 1);
            //console.log(this.ChapList)
            return this.$message.success("删除小节成功");
          }
        }
        return this.$$message.error("删除小节失败");
      },

      //交互//将新生成的章节表提交至后端存储功能
      async setChap() {
        let res = await this.$http.post("setchaplist", {
          chaplist: this.ChapList,
          couid: window.sessionStorage.getItem("couid")
        });
        console.log(res)
        if (res.data.code != 200) {
          return this.$message.error("上传章节表失败！");
        }
        this.$message.success("上传章节表成功");
        this.setChapVisible = false;
      }
    }
  };
</script>

<style scoped>
  .addsecbutton {
    margin-bottom: 25px;
  }
  .a1 {
    margin-right: 8px;
  }
</style>
